package com.atguigu.mapreduce.reducejoin;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;

import java.io.IOException;

public class TableMapper extends Mapper<LongWritable, Text, Text, TableBean> {

    private String filename;
    private Text outK = new Text();
    private TableBean outV = new TableBean();

    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        // 初始化 order pd

        // 输入有两个文件，改用FileSplit（默认InputSplit）
        FileSplit split = (FileSplit) context.getInputSplit();
        // 获取对应文件名称
        filename = split.getPath().getName();
    }

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        // 1 获取一行
        String line = value.toString();

        // 2 判断是哪个文件
        if (filename.contains("order")) {
            // 订单表 order

            // 切分
            String[] split = line.split("\t");

            // 封装 outK outV
            outK.set(split[1]);
            outV.setId(split[0]);
            outV.setPid(split[1]);
            outV.setAmount(Integer.parseInt(split[2]));
            outV.setPname("");// order表没Pname,赋一个空值
            outV.setFlag("order");

        } else {
            // 商品表 pd

            // 切分
            String[] split = line.split("\t");

            // 封装 outK outV
            outK.set(split[0]);
            outV.setId("");
            outV.setPid(split[0]);
            outV.setAmount(0);
            outV.setPname(split[1]);
            outV.setFlag("pd");

        }

        // 写出
        context.write(outK,outV);
    }
}
